#! python3

import os
import sys
import chardet
import pathlib


g_tagFolder = os.path.abspath(r"E:\Users\yinxunqian\Documents\Xcl_members\work-fred\shichangbu\newemail")

g_source = g_tagFolder
g_target = g_tagFolder
#g_error = g_tagFolder

g_afterfix = "r"

g_maxlength = 50000

g_i = 1 

def SequnceStr(num, targetlength):
    outstr = "0" * targetlength + str(num)
    return outstr[(-1)*targetlength:]

def DoActionOnFolder(path):
    itemlist = os.listdir(path)
    for f in itemlist:
        tmppath = path + "\\" + f
        if(os.path.isfile(tmppath)):
            # do action
            print("is file")
            OneToMore(tmppath, g_maxlength)
        if(os.path.isdir(tmppath)):
            # folder
            DoActionOnFolder(tmppath)


def main():
    print("***process start!")
    # 1 check file list
    DoActionOnFolder(g_tagFolder)
    print("***process end!")
    return True

'''
hello
filename + g_afterfix + SequnceStr(ci,3) + ".txt"
'''
def OneToMore(filepath, maxlength):
    #ci = copy index
    ci = 1
    i = 0
    _base = os.path.basename(filepath)
    _file, _ext = os.path.splitext(filepath)

    with open(filepath, "r+", encoding="utf-8",errors='ignore') as fs :
        for l in fs.readlines():
            if(i < maxlength):
                i = i + 1
                print(str(ci) + "_" + str(i))
            else:
                i = 0
                ci = ci + 1
            with open((filepath.replace(_base, _base.replace(_ext,"",1) + g_afterfix + SequnceStr(ci,3) + _ext, 1)),'a+', encoding='utf8') as ft:
                    ft.write(l)
    
    # remove this file
    os.remove(filepath)


# OneToMore(g_tagFolder + "\\300w.txt", g_maxlength )
main()


